package com.ruoyi.hospital.utils;

import com.github.pagehelper.util.StringUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

	private static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
	private static final String DEFAULT_SALT = "d03a104a99c7734d6e7be5a1de5c8050";
	
	public static String md5(String str) {
		
		if (str == null) {
			return null;
		}
		
		byte[] digest = null;
		
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            digest  = md5.digest(str.getBytes("utf-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        int j = digest.length;
        int k = 0;
		char strc[] = new char[j * 2];
		
		for (int i = 0; i < j; i++) {
			byte byte0 = digest[i];
			strc[k++] = hexDigits[byte0 >>> 4 & 0xf];
			strc[k++] = hexDigits[byte0 & 0xf];
		}
		
		return new String(strc);
	}
	
	public static String md5(String str, String salt) {
		if (str == null) {
			return null;
		}
		
		return md5(str + salt);
	}
	
	public static String saltedMd5(String str) {
		return md5(str, DEFAULT_SALT);
	}
	
	/**
	 * 生成登录密码
	 * @return
	 */
	public static String generatePassword(String pwd) {
		if (StringUtil.isEmpty(pwd)) {
			return null;
		}
		
		// 密码规则不可改，否则无法登录
		return saltedMd5(md5(DEFAULT_SALT.substring(10), pwd));
	}
}
